package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.dao.DevAmTicketDao;
import com.sugon.dao.DevAmTicketItemDao;
import com.sugon.entity.DevAmTicketEntity;
import com.sugon.entity.DevAmTicketItemEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.modules.device.consts.DevMaintenanceItemExecuteStatus;
import com.sugon.modules.device.consts.DevMaintenanceTicketStatus;
import com.sugon.modules.device.model.vo.DevAmTicketVO;
import com.sugon.modules.device.model.vo.DevTemMaintenanceTicketParamVO;
import com.sugon.modules.device.model.vo.DevTemPmTicketAdjustParam;
import com.sugon.service.DevAmTicketItemService;
import com.sugon.service.DevAmTicketService;
import com.sugon.utils.Constant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备自主维护工单数据Service实现类
 *
 * @author YuXD
 * @date 2023-01-23
 */
@Service("devAmTicketService")
public class DevAmTicketServiceImpl implements DevAmTicketService {

    @Resource
    private DevAmTicketDao devAmTicketDao;
    @Resource
    private DevAmTicketItemDao devAmTicketItemDao;
    @Resource
    private DevAmTicketItemService devAmTicketItemService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DevAmTicketEntity addTemporaryPlan(DevTemMaintenanceTicketParamVO temPlanParam) {
        /*
            1、保存临时维护计划
            2、保存临时维护计划明细
            3、给对应车间的生产班组长发送企业微信消息
         */
        // 创建维护工单基础信息
        DevAmTicketEntity am = new DevAmTicketEntity();
        am.setDevId(temPlanParam.getDevId());
        am.setWorkshop(temPlanParam.getWorkshopId());
        am.setStartTime(DateUtil.beginOfDay(temPlanParam.getStartDate()));
        am.setEndTime(DateUtil.endOfDay(temPlanParam.getEndDate()));
        am.setStatus(DevMaintenanceTicketStatus.DISPATCHING);
        am.setTicketType(temPlanParam.getTicketType().name());
        am.setWeekOfYear(DateUtil.weekOfYear(temPlanParam.getStartDate()));
        am.setYearly(DateUtil.year(am.getStartTime()));
        // 1、保存临时维护计划
        if (save(am) > 0) {
            // 2、保存临时维护计划明细
            DevAmTicketItemEntity amTicketItem = new DevAmTicketItemEntity();
            amTicketItem.setProblemDesc(temPlanParam.getDesc());
            amTicketItem.setStep(temPlanParam.getStep());
            amTicketItem.setDevMainTicketId(am.getId());
            amTicketItem.setStatus(DevMaintenanceItemExecuteStatus.UN);
            // 默认无异常，实际实施过程中可修改
            amTicketItem.setCheckResult(0);
            devAmTicketItemService.save(amTicketItem);
        }
        return am;
    }

    @Override
    public DevAmTicketEntity adjustTemporaryPlan(DevTemPmTicketAdjustParam temPlanParam) {
        DevAmTicketEntity matchedAmTicket = queryObject(temPlanParam.getPmTicketId());
        Assert.notNull(matchedAmTicket);
        matchedAmTicket.setStartTime(DateUtil.beginOfDay(temPlanParam.getStartDate()));
        matchedAmTicket.setEndTime(DateUtil.endOfDay(temPlanParam.getEndDate()));
        matchedAmTicket.setFinalEndTime(matchedAmTicket.getEndTime());
        matchedAmTicket.setWeekOfYear(DateUtil.weekOfYear(matchedAmTicket.getStartTime()));
        matchedAmTicket.setYearly(DateUtil.year(matchedAmTicket.getStartTime()));
        if (update(matchedAmTicket) > 0) {
            List<DevAmTicketItemEntity> amItemList = devAmTicketItemService.queryByTicketId(temPlanParam.getPmTicketId());
            if (CollectionUtil.isNotEmpty(amItemList)) {
                for (DevAmTicketItemEntity pmItem : amItemList) {
                    pmItem.setProblemDesc(temPlanParam.getDesc());
                    pmItem.setStep(temPlanParam.getStep());
                    devAmTicketItemService.update(pmItem);
                }
            } else {
                // 2、保存临时维护计划明细
                DevAmTicketItemEntity devMaintenanceTicketItem = new DevAmTicketItemEntity();
                devMaintenanceTicketItem.setProblemDesc(temPlanParam.getDesc());
                devMaintenanceTicketItem.setStep(temPlanParam.getStep());
                devMaintenanceTicketItem.setDevMainTicketId(matchedAmTicket.getId());
                devMaintenanceTicketItem.setStatus(DevMaintenanceItemExecuteStatus.UN);
                // 默认无异常，实际实施过程中可修改
                devMaintenanceTicketItem.setCheckResult(0);
                devAmTicketItemService.save(devMaintenanceTicketItem);
            }
        }
        return matchedAmTicket;
    }

    @Override
    public int countUnCompleteTicketNum(SysUserEntity loginUser) {
        Map<String, Object> params = MapUtil.newHashMap();
        // 查看本月的工单
        DateTime current = DateUtil.date();
        params.put("startTime", DateUtil.formatDateTime(DateUtil.beginOfMonth(current)));
           /*
                默认显示当月维护工单， 如果月末这一天所在的周末跨月了。
                那么需要将统计的截止时间推迟到周末
             */
        Date endTime = DateUtil.endOfMonth(current);
        Date endOfWeek = DateUtil.endOfWeek(endTime);
        if (DateUtil.month(endTime) + 1 == DateUtil.month(endOfWeek)) {
            endTime = endOfWeek;
        }
        params.put("endTime", DateUtil.formatDateTime(endTime));
        /*
            维修组长可以看到车间下所有的维护工单执行情况
            维修工只看分配给自己的
         */
        if (loginUser.getLeader() != 1) {
            params.put("executor", loginUser.getUserId());
        } else {
            params.put("deptCode", loginUser.getDeptCode());
        }
        // 只显示未分派、未执行和超期未完成的维护工单数
        params.put("statusList", CollectionUtil.newArrayList(DevMaintenanceTicketStatus.DISPATCHING, DevMaintenanceTicketStatus.WAIT_EXECUTE, DevMaintenanceTicketStatus.MAINTAINING, DevMaintenanceTicketStatus.DELAY_APPLYING, DevMaintenanceTicketStatus.DELAY_MAINTAINING, DevMaintenanceTicketStatus.OVERTIME));
        return queryAllTotal(params);
    }

    /**
     * queryObject
     *
     * @param id 主键
     * @return
     */
    @Override
    public DevAmTicketEntity queryObject(String id) {
        return devAmTicketDao.queryObject(id);
    }

    /**
     * queryAll
     *
     * @param map 参数
     * @return
     */
    @Override
    public List<DevAmTicketVO> queryAll(Map<String, Object> map) {
        return devAmTicketDao.queryAll(map);
    }

    /**
     * queryAllTotal
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryAllTotal(Map<String, Object> map) {
        return devAmTicketDao.queryAllTotal(map);
    }

    /**
     * queryList
     *
     * @param map 参数
     * @return
     */
    @Override
    public List<DevAmTicketEntity> queryList(Map<String, Object> map) {
        return devAmTicketDao.queryList(map);
    }

    /**
     * queryTotal
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return devAmTicketDao.queryTotal(map);
    }

    /**
     * save
     *
     * @param devAmTicket 实体
     * @return
     */
    @Override
    public int save(DevAmTicketEntity devAmTicket) {
        devAmTicket.setId(RandomUtil.randomString(32));
        devAmTicket.setGmtCreate(DateUtil.date());
        devAmTicket.setDelFlag(Constant.IS_NOT_DEL_INT);
        devAmTicket.setIsUrged(0);
        devAmTicket.setRepairCode(generateUniqueCode());
        devAmTicket.setFinalEndTime(devAmTicket.getEndTime());
        return devAmTicketDao.save(devAmTicket);
    }

    /**
     * generateUniqueCode
     *
     * @return
     */
    @Override
    public String generateUniqueCode() {
        // 构建工单编码前缀
        String ticketCodePrefix = ErmsCodePrefix.MAINTENANCE_TICKET_CODE_PREFIX + com.sugon.modules.utils.DateUtil.today() + "-";
        // 获取已上述前缀开头的最新工单编码
        String lastestMaintenanceCode = devAmTicketDao.getLastestMaintenanceCode(ticketCodePrefix);
        return com.sugon.modules.utils.StrUtil.increase(lastestMaintenanceCode, ticketCodePrefix, 4, 1);
    }

    /**
     * update
     *
     * @param devAmTicket 实体
     * @return
     */
    @Override
    public int update(DevAmTicketEntity devAmTicket) {
        return devAmTicketDao.update(devAmTicket);
    }

    /**
     * delete
     *
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        // 先删除维护工单项
        devAmTicketItemDao.deleteByTicketId(id);
        // 再删除维护工单
        return devAmTicketDao.delete(id);
    }

    /**
     * deleteBatch
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        return devAmTicketDao.deleteBatch(ids);
    }

}
